#include "UserManager.h"

User::User(int socket, const string &username)
    : socket(socket), username(username), online(true)
{
}

int User::getSocket() const
{
    return socket;
}

string User::getUsername() const
{
    return username;
}

void User::setUsername(const string &username)
{
    this->username = username;
}
bool User::isOnline() const
{
    return online;
}

void User::setOffline()
{
    online = false;
}

void UserManager::addUser(int socket, const string &username)
{
    lock_guard<mutex> lock(_mutex);
    users[socket] = make_shared<User>(socket, username);
}

void UserManager::removeUser(int socket)
{
    lock_guard<mutex> lock(_mutex);
    if (users.find(socket) != users.end())
    {
        users[socket]->setOffline();
        users.erase(socket);
    }
}

shared_ptr<User> UserManager::getUser(int socket)
{
    lock_guard<mutex> lock(_mutex);
    auto it = users.find(socket);
    if (it != users.end())
    {
        return it->second;
    }
    return nullptr;
}

vector<shared_ptr<User>> UserManager::getAllUsers()
{
    lock_guard<mutex> lock(_mutex);
    vector<shared_ptr<User>> result;
    for (auto &pair : users)
    {
        result.push_back(pair.second);
    }
    return result;
}
